import React, {useEffect, useState} from 'react';
import {PageContainer} from '@ant-design/pro-components';
import {Avatar, Button, Card, Form, Input, message, Space, Tabs} from 'antd';
import {LockOutlined, UserOutlined} from '@ant-design/icons';
import {useModel} from '@umijs/max';
import {updatePasswordUsingPost} from "@/services/backend/userController";
import {history} from "@@/core/history";

const {TabPane} = Tabs;

/**
 * 个人设置页
 * @constructor
 */
const Account: React.FC = () => {
  const {initialState} = useModel('@@initialState');
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (initialState?.currentUser) {
      form.setFieldsValue({
        userName: initialState.currentUser.userName,
        userAccount: initialState.currentUser.userAccount,
        avatarUrl: initialState.currentUser.avatarUrl
      });
    }
  }, [initialState?.currentUser]);

  // 更新基本信息
  const handleUpdateInfo = async (values: any) => {
    setLoading(true);
    try {
      // TODO: 调用后端API更新用户信息
      message.success('基本信息更新成功');
    } catch (error: any) {
      message.error('更新失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handleUpdatePassword = async (values: any) => {
    if (values.newPassword !== values.confirmPassword) {
      message.error('两次输入的密码不一致');
      return;
    }
    setLoading(true);
    try {
      const res = await updatePasswordUsingPost({...values})
      if (res.code === 0) {
        message.success('密码修改成功');
        passwordForm.resetFields();
        // 退出登录
        history.replace({
          pathname: '/user/login',
        });
      }
    } catch (error: any) {
      message.error('密码修改失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer>
      <Card extra={<><a onClick={() => history.go(-1)}>返回</a></>}>
        <Tabs defaultActiveKey="basic">
          <TabPane tab="基本信息" key="basic">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleUpdateInfo}
              style={{maxWidth: 600, margin: '0 auto'}}
            >
              <Form.Item style={{textAlign: 'center'}} name="avatarUrl">
                <Space direction="vertical" align="center">
                  <Avatar size={100} src={initialState?.currentUser?.avatarUrl}/>
                  <Button type="link">更换头像</Button>
                </Space>
              </Form.Item>
              <Form.Item
                name="userName"
                label="用户名"
                rules={[{required: true, message: '请输入用户名'}]}
              >
                <Input prefix={<UserOutlined/>} placeholder="请输入用户名"/>
              </Form.Item>
              <Form.Item
                name="userAccount"
                label="账号"
              >
                <Input prefix={<UserOutlined/>} placeholder="请输入账号" disabled={true}/>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading} block>
                  保存修改
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="修改密码" key="password">
            <Form
              form={passwordForm}
              layout="vertical"
              onFinish={handleUpdatePassword}
              style={{maxWidth: 600, margin: '0 auto'}}
            >
              <Form.Item
                name="oldPassword"
                label="当前密码"
                rules={[{required: true, message: '请输入当前密码'}]}
              >
                <Input.Password prefix={<LockOutlined/>} placeholder="请输入当前密码"/>
              </Form.Item>
              <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                  {required: true, message: '请输入新密码'},
                  {min: 6, message: '密码长度不能小于6位'}
                ]}
              >
                <Input.Password prefix={<LockOutlined/>} placeholder="请输入新密码"/>
              </Form.Item>
              <Form.Item
                name="confirmPassword"
                label="确认新密码"
                rules={[
                  {required: true, message: '请确认新密码'},
                  {min: 6, message: '密码长度不能小于6位'}
                ]}
              >
                <Input.Password prefix={<LockOutlined/>} placeholder="请确认新密码"/>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading} block>
                  修改密码
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </PageContainer>
  );
};

export default Account;
